const fs = require('fs');
const fileService = require('../service/file.service');
const momentService = require('../service/moment.service');
const { PICTURE_PATH } = require('../constants/file-path');
class MomentController {
  async create (ctx, next) {
    // 获取数据(user_id, content)
    const { id } = ctx.user;
    const { content } = ctx.request.body;
    const result = await momentService.create(content, id)
    ctx.body = result;
  }
  async detail (ctx, next) {
    const momentId = ctx.params.momentId;
    const result = await momentService.getMomentById(momentId);
    ctx.body = result;
  }
  async list (ctx, next) {
    // 获取数据 offset/size
    const { offset, size } = ctx.query;
    const result = await momentService.getMomentList(offset, size);
    ctx.body = result;
  }
  async update (ctx, next) {
    // 1. 获取参数
    const { momentId } = ctx.params;
    const { content } = ctx.request.body;
    // 修改参数
    const result = await momentService.update(content, momentId);
    ctx.body = result;
  }
  async remove (ctx, next) {
    const { momentId } = ctx.params;
    const result = await momentService.remove(momentId);
    ctx.body =  result;
  }
  async addLabels (ctx, next) {
    // 1. 获取标签和动态数据
    try {
      const { labels } = ctx;
      const { momentId } = ctx.params;
      for (let label of labels) {
        // 2.1 判断标签是否已经和动态有关系
        const isExists = await momentService.hasLabel(momentId, label.id);
        if (!isExists) {
          await momentService.addLabel(momentId, label.id);
        }
      }
      ctx.body = '给动态添加标签成功~';
    } catch (err) {
      console.log(err);  
    }
  }
  async fileInfo (ctx, next) {
    let { filename } = ctx.params;
    const fileInfo = await fileService.getFileByFilename(filename);
    const { type } = ctx.query;
    const types = ["small", "middle", "large"];
    if (types.some(item => item === type)) {
      filename = filename + '-' + type;
    }
    ctx.response.set('content-type', fileInfo.mimetype);
    ctx.body = fs.createReadStream(`${PICTURE_PATH}/${filename}`); // 写入文件数据库
  }
}

module.exports = new MomentController();